<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Util\SqlServerUtil;
use App\Util\Common;
use App\Services\OSS;
use App;
use Illuminate\Support\Facades\Cookie;
use App\Util\GetMac;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;

use Illuminate\Support\Facades\Log;


use App\Http\Model\JewelleryInfo as JewelleryInfo;

class AdminController extends Controller
{
    protected $response = [
    		"Error" => 0,
    		"Message" => "Success!",
    		"Data" => []
	];

	protected $SqlServer = null;

	public function __construct(Request $request){
		
		$temp = SqlServerUtil::getModel($request);
		if($temp){
			$this->SqlServer = $temp['SqlServer'];
		}
	}

	//获取用户列表
	public function getUserLists(Request $request){
// 		dd(22);
		$page= $request ->get('page');
		if(!isset($page)) $page =1;
		$limit= $request ->get('limit');
		if(!isset($limit)) $limit =20;
		$pages = ($page-1)* $limit;
		
		$username = $request ->get('username');
		$search ='';
		if ($request->has('keyword') and $request->keyword != '') {
			$search = " and (u.username like '%".$request->keyword."%' or  u.customername like '%".$request->keyword."%' or  u.fdeptname like '%".$request->keyword."%' )";
		}
		$fdeptnameStr ='';
		if ($request->has('fdeptname') and $request->fdeptname != '') {
			$fdeptnameStr = " and (u.fdeptname =  '{$request->fdeptname}' )";
		}
		//u.status=1
		if($username  == 'manager'){
			$sql ="SELECT TOP {$limit} * FROM gz_admin u where u.id NOT IN (SELECT TOP $pages u.id FROM gz_admin u where 1=1 {$search} {$fdeptnameStr} ) and 1=1 {$search} {$fdeptnameStr} ";
			$countSql ="SELECT COUNT(1) AS total FROM gz_admin u where 1=1 {$search} {$fdeptnameStr} ";
		}else{
			$sql ="SELECT TOP {$limit} * FROM gz_admin u where u.id NOT IN (SELECT TOP $pages u.id FROM gz_admin u where 1=1 and u.username !='manager' {$search} {$fdeptnameStr} ) and 1=1 and u.username !='manager' {$search} {$fdeptnameStr} ";
			$countSql ="SELECT COUNT(1) AS total FROM gz_admin u where 1=1 and u.username !='manager' {$search} {$fdeptnameStr} ";
		}
		
		$res = SqlServerUtil::execTosql($this->SqlServer,$sql);
		if($res){
			
			foreach ($res as $k =>$v)
			{
				$res[$k]['password'] = base64_decode($v['password']);
			}
		}
		$count = SqlServerUtil::execTosql($this->SqlServer, $countSql);
		$this->response['total'] = $count ? $count[0]['total']:0;
		$this->response['size'] = $page;
		$last_page =0;
		if($count && count($count)>0){
			$last_page = ceil($count[0]['total']/$limit);
		}
		
		$this->response['result'] = $res;
		$this->response['last_page'] =$last_page;
		return response()->json($this->response);
	}

	

	public function updatePassword(Request $request)
	{
		$res = SqlServerUtil::update($this->SqlServer,"yd_admin",['password' => $request->get('password')],['id' => $request->get('id')]);
		if($res){
			$this->response['message'] = "Update Success";
		}else{
			$this->response['code'] = 400;
			$this->response['message'] = "Update Fail";
		}
		return response()->json($this->response);
	}


	//获取单个用户信息
	public function getUserInfo($id)
	{
		$this->response['result'] = SqlServerUtil::get($this->SqlServer,"yd_admin",['id' => $id],['*']);
		return response()->json($this->response);
	}

	public function adminIndex(Request $request)
	{
		$page= $request ->get('page');
		if(!isset($page)) $page =1;
		$limit= $request ->get('limit');
		if(!isset($limit)) $limit =20;
		$pages = ($page-1)* $limit;
		
		$search ='';
		if ($request->has('keyword') and $request->keyword != '') {
			$search = " and e.LoginEmail like '%".$request->keyword."%'";
		}
		
		$sql ="select TOP $limit e.employeeid, e.employeeName,e.LoginEmail,e.CreatedDate from employee e where 
				e.employeeID Not in (SELECT TOP $pages e.employeeID  FROM employee e where e.employeeID>0 {$search} order by e.employeeid desc)
and e.employeeID>0 {$search} order by e.employeeid desc ";
		
		$m = SqlServerUtil::exec($this->SqlServer, $sql);
		
		$countSql ="SELECT COUNT(1) AS total from employee e where e.employeeID>0 {$search} ";
		$count = SqlServerUtil::exec($this->SqlServer, $countSql);
		
		$this->response['total'] = $count ? $count[0]['total']:0;
		$this->response['size'] = $page;
		
		$last_page =0;
		if($count && count($count)>0){
			$last_page = ceil($count[0]['total']/$limit);
		}
		
		$this->response['result'] = $m?$m:[];
		$this->response['last_page'] =$last_page;
		return response()->json($this->response);
		
		
	}
	
	/**
	 * 聚一科技 ^_^
	 * 删除
	 * @date: 2020年10月20日
	 * @author: lq
	 * @version:App V2.0
	 */
	public function delUser(Request $request)
	{
		$param = $request->all();
		$id=$param['id'];
		$opername = isset($param['opername'])?$param['opername']:'';
		
		Log::useFiles(storage_path('logs/job/delUser.log'));
		Log::info(getCurrentTime()."---删除操作 用户名{$request->username}, 内码{$id}--URL接口地址  :" .$request->url().'  ----参数：' .urldecode(http_build_query($request->all())) ."\r\n \r\n");

		SqlServerUtil::execSql($this->SqlServer,"DELETE gz_admin   WHERE id = {$id} and username != 'manager' ");
		$qkid1 = sqlsrv_query($this->SqlServer,"DELETE gz_user_group WHERE userid = '{$id}' ");
		$this->writeLog('账号列表','删除' , 13000 , ($param) ,$opername );
		return response()->json($this->response);
	}
	
	/**
	 * 文件用途描述
	 * @date: 2019年10月14日 上午10:22:43
	 * @author: yy
	 */
	public function addUser(Request $request){
		$username =$request->get("username");
		$pass =$request->get("password");
		$all = $request->all();
		$opername = $request->get("opername") ?$request->get("opername"):'';
		unset($all['db']);
		unset($all['opername']);
		if(empty($username)){
			return response()->json(Common::errorResponse(452));
		}
		$pass = base64_encode($pass);
		$all['password'] = $pass;
		//用户名是否存在
		$user = SqlServerUtil::exec($this->SqlServer,"select id,status from gz_admin where username='{$username}' ",2);
		if(!empty($user['status'])){return response()->json(Common::errorResponse(456));}
		$all = _unsetNull($all);
		if(!empty($user) ){
			//更新
			if($user['status'] == 0){
				$up = SqlServerUtil::update($this->SqlServer,"gz_admin",array_merge($all,['create_time'=>getCurrentTime(),'update_time'=>'','status'=>1]), ['username' =>$username]);
				if($up){
					return response()->json(Common::successResponse(200,'成功'));
				}else{
					showMsg(400,'失败');
				}
			}
		}
		$res= SqlServerUtil::sqlsrvCreateTosql($this->SqlServer,'gz_admin',array_merge($all,['create_time'=>getCurrentTime(),'module'=>1,'moduleDetail'=>'10,11,12']));
		if($res){
			$this->writeLog('账号列表','新增' , 13000 , ($all) ,$opername );
			return response()->json(Common::successResponse(200,'添加成功'));
		}else {
			return response()->json(Common::errorResponse(703));
		}
	}
	
	/**
	 * 聚一科技 ^_^
	 *  修改
	 * @date: 2020年10月20日
	 * @author: lq
	 * @version:App V2.0
	 */
	public function editUser(Request $request)
	{
		$temp = $request->all();
		$all = _unsetNull($temp);
		$id= $all['id'];
		$opername = isset($all['opername']) ?$all['opername']:'';
		unset($all['id']);
		unset($all['db']);
		unset($all['opername']);
		
		$all['password'] = base64_encode($all['password']);
		
		$up = SqlServerUtil::exeupdateTosql($this->SqlServer,"gz_admin",array_merge($all,['update_time'=>getCurrentTime()]), ['id' =>$id]);
		if($up){
			$this->writeLog('账号列表','编辑' , 13000 , ($all),$opername  );
			return response()->json(Common::successResponse(200,'编辑成功'));
		}else{
			showMsg(400,'修改失败');
		}
	}
	
	
	
	
	
	
	//日志记录
	public function writeLog( $fmkname='',$methodOper ='', $objectid =0, $fobj, $opername='', $finterid = 0 ){
		$arr=[
				'fname' => $fmkname, //模块
				'methodOper'=> $methodOper, //功能
				'objectid'=>$objectid, //功能 代码
				'fobj'=>is_array($fobj)?json_encode($fobj, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE):$fobj, //详情信息
				
				'opername'=> $opername, //操作人
				'finterid'=> $finterid, //订单内码
				'create_at'=>getCurrentTime(),
				'fip' =>  real_ip(),
		];
		
		
		$in = SqlServerUtil::sqlsrvCreateTosql($this->SqlServer,'gz_Operlog',$arr);
		
		return  $in;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function deviceEdit(Request $request)
	{
		
		
		
		
		
		
	}
	
	
	public function deviceAuth(Request $request)
	{
		$message='授权成功';
		$param= $request->all();
		/*
		 *username" => "123"
		  "platfrom" => 2
		  "level" => 1
		  "is_auth" => 0
		  "ip" => "223.104.63.186"
		  "id" => 4
		  "device_id" => "CA-15-68-D0-FF-80"
		 */
		$is_auth = empty($param['is_auth'])?1:0;
		if(!empty($param['is_auth'])){
			$message = "未授权";
		}
		if($param){
			$data=['is_auth'=>$is_auth];
			if(empty($param['device_id']) && empty($param['ip'])){
				/* $sql ="select d.device_id,d.is_auth,d.platfrom,d.ip from yd_device d where d.id ='{$param['id']}' ";
				$m = SqlServerUtil::exec($this->SqlServer, $sql);
				if(empty($m)){
					$insert =['admin_id'=>$param['id'],'is_auth'=>1];
					SqlServerUtil::insert($this->SqlServer,'yd_device',$insert);
				} */
				return response()->json(Common::errorResponse(460));
			}
			
			$where = ['admin_id'=>$param['id'],'device_id'=>$param['device_id'],'ip'=>$param['ip'],'platfrom'=>$param['platfrom']];
			SqlServerUtil::kshiupdate($this->SqlServer,'yd_device',$data,$where);
			
			return response()->json(Common::successResponse(200,$message));
		}
		return response()->json(Common::successResponse(200,$message));
		
	}
	
	
	function getMAC() {
		@exec("ipconfig /all",$array);
		dd($array);
		$Tmpa =0;
		for($Tmpa;$Tmpa<count($array);$Tmpa++){
			if(preg_match('/^.*/',"Physical",$matches)){
				//$mac=explode(":",$array[$Tmpa]);
				return $matches;
			}
		}
	}
	
	public function togbk($str){
		$encode =mb_detect_encoding($str, array("ASCII","GB2312","UTF-8","GBK","BIG5"));
		$str = iconv($encode,"UTF-8//IGNORE",$str);
		return ($str);
	}
	
	
	public function yy(Request $request)
	{
		
	}
	
	
	function GetMacAddr()
	{
		$return_array = array();
		$temp_array = array();
		$mac_addr = "";
		
		@exec("arp -a",$return_array);
	
		foreach($return_array as $value)
		{
			if(strpos($value,$_SERVER["REMOTE_ADDR"]) !== false &&
					preg_match("/(:?[0-9a-f]{2}[:-]){5}[0-9a-f]{2}/i",$value,$temp_array))
			{
				$mac_addr = $temp_array[0];
				break;
			}
		}
		
		return ($mac_addr);
	}
	

	public  function moduleAuth(Request $request){
		$prama= $request->all();
		
		dd($prama);
		
		
	}
	
	public  function moduleAuthAdd(Request $request){
		$prama= $request->all();
		if(!$prama){return response()->json(Common::errorResponse(401));}
		$id =$prama['id'];
		$platfrom =$prama['platfrom'];
		$username =$prama['username'];
		$sql ="select a.id,a.username,a.password,a.level,a.create_time,d.device_id,d.is_auth,d.platfrom,d.list,d.blist,d.ip from yd_admin a left join yd_device d on d.admin_id=a.id where a.status =1 and a.id='{$id}' and a.username='{$username}' and d.platfrom ='{$platfrom}'";
		$m = SqlServerUtil::exec($this->SqlServer, $sql);
		$m = $m[0];
		if(strpos($m['list'], ',')){
			$m['list'] = explode(',', $m['list']);
		}else{
			$m['list'] =$m['list'] ? explode(',', $m['list']) : [];
		}
		if(strpos($m['blist'], ',')){
			$m['blist'] = explode(',', $m['blist']);
		}else{
			$m['blist'] =$m['blist'] ? explode(',', $m['blist']) : [];
		}
			
		$this->response['result'] = $m;
		return response()->json($this->response);
		
	}
	
	public  function moduleAuthEdit(Request $request){
		$prama= $request->all();
// 		dd($prama);
		$username = $prama['username'];
		$id = $prama['id'];
		$platfrom = $prama['platfrom'];
		$list  = join($prama['list'],',');
		$blist  = join($prama['blist'],',');
		$m = SqlServerUtil::kshiupdate($this->SqlServer,'yd_device',['list'=>$list,'blist'=>$blist],['admin_id'=>$id,'platfrom'=>$platfrom]);
		return response()->json(Common::successResponse(200,'开通成功'));
	}
	public  function getModule(Request $request){
		$sql ="select id ,name,type from yd_auth where type>0";
		$m = SqlServerUtil::exec($this->SqlServer, $sql);
		$this->response['result'] = $m;
		return response()->json($this->response);
	}
	
	public  function getButton(Request $request){
		$sql ="select a.id ,a.name,a.pid,t.name dname,t.id did ,t.pid pdid from yd_auth a left join (select id,name,pid from yd_auth t where pid>0 ) t on t.pid =a.id  where a.type>0 ";
		$m = SqlServerUtil::exec($this->SqlServer, $sql);
		$res = [];
		foreach ($m as $k =>$v)
		{
			if($v['id'] == $v['pdid']){
				$res[$v['name']][$v['did']]=$v['dname'];
			}
		}

		$this->response['result'] = $res;
		return response()->json($this->response);
	}
	
	
	function selectTree($data,$id)
	{ 
		$treeid = array(); 
		foreach($data as $key=>$val) 
		{ 
			if($id==$val['parentid']) 
			{ 
				$treeid[] = $val['id']; 
				$this->selectTree($data,$val['id']); 
			} 
		} 
		return $treeid; 
	}

}
